package com.letoken.platform.pub.annotation.content;

import com.letoken.platform.pub.enums.LetokenApiResponseEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.web3j.abi.datatypes.Bool;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Component
public class ContentValidator implements ConstraintValidator<ContentCheck, Object> {


    private ContentEnum ce;

    private Boolean allowNull;


//    private final static String COMM = "[ _`!@#$%^&*()+=|{}’:;’,.<>/?！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";

    private final static String COMM = "[_`!@#$%^&*()+=|{}’:;’.<>/?！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
    private final static Pattern p = Pattern.compile(COMM);



    @Override
    public void initialize(ContentCheck constraintAnnotation) {
        ce = constraintAnnotation.type();
        allowNull = Boolean.valueOf(constraintAnnotation.allowNull());
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context ) {
        if (ObjectUtils.isEmpty(value)) {
            // 空值不校验
            if (allowNull){
                return true;
            }
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("80000007").addConstraintViolation();
            return false;
        }

        try {
            if (ce == ContentEnum.LOCAL_CONTENT){
                return checkStr((String) value);
            }else if (ce == ContentEnum.CONTENT){
                return true;
            } else if (ce == ContentEnum.IMAGE){
                return true;
            }else {
                log.info("审核内容类型不匹配");
            }
        } catch (Exception e) {
            log.error("内容审核错误",e);
        }
        return false;
    }



    private Boolean checkStr(String s){
        Matcher m = p.matcher(s);
        return !m.find();
    }


    private Boolean checkImg(){
        return true;
    }








}
